



const express = require("express");
const route = express.Router();

const advModel = require("../db/model/advModel")
const path = require("path")
const fs =require("fs")

const isLoginMiddle = require("../middleware/isLoginMiddle");



//删除广告 接口
route.delete("/deleteAdv", isLoginMiddle, async (req, res) => {

  const { _id } = req.query
  // console.log(req.query);
  // console.log(_id);

  //删除数据库对应的图片
  //首先去数据库查询当前的_id对应的图片名
  try {
    //首先去数据库查询当前的_id对应的图片名
    const {
      advHref
    } = await advModel.findOne({
      _id
    })
    

    const imgName = advHref.split("/")[2];

    //删除这个图片
    // console.log(path.resolve(__dirname, "../upload", imgName));
    fs.unlink(path.resolve(__dirname, "../upload", imgName), () => {
      console.log("删除成功");
    })
  } catch (e) {

   console.log("删除图片逻辑有错" + e.message);
    return res.send({
      code: 10001,
      msg: "删除图片逻辑有错" + e.message,
      data: null
    })
  }
  
    //删除数据库的数据
    try {
      const deleteResult = await advModel.deleteOne({
        _id
      })
  
      res.send({
        code: 10000,
        msg: "删除广告列表成功",
        data: null
      })
    } catch (e) {
      console.log("删除广告列表失败" + e.message);
      res.send({
        code: 10001,
        msg: "删除广告列表失败" + e.message,
        data: null
      })
    }


})


module.exports = route;